package com.scisoft.scan.dy;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.provider.Settings;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.scisoft.scan.control.MainMenuActivity;
import com.scisoft.scan.control.StringInputActivity;
import com.scisoft.scan.data.UpdateVersionInfo;
import com.scisoft.scan.db.LoginDBHelper;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.util.CrashHandlerUtil;
import com.scisoft.scan.util.UpdateManager;
import com.scisoft.scan.ws.SysParameter;
import com.scisoft.scan.ws.WebServiceHelper;

import static android.Manifest.permission.MANAGE_EXTERNAL_STORAGE;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.READ_PHONE_STATE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

public class LoginActivity extends AppCompatActivity {

    private String TAG = "BugCao";

    private  EditText accountText = null;//账号输入框
    private  EditText passwordText = null;//密码输入框
    private TextView scSequenceText = null;//手机序列号显示区
    private LoginDBHelper loginDBHelper = null;//登录助手
    private CheckBox cb_login_remember = null;//记住密码选择框
    private UpdateManager mUpdateManager;//自动升级组件
    private UpdateVersionInfo updateInfo;//自动升级信息
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_login);
        //验证权限
        requestInstallPermision();
        //test
        //init();
    }

    private void requestStoragePermision(){
        Log.d(TAG,"Login");
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            Log.d(TAG,"第一层if");
            int permission = checkSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE");
            //没权限弹出是否允许权限弹窗
            if (permission != PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG,"第二层if");
                //requestPermissions(new String[]{"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"}, REQUEST_WRITE_EXTERNAL_STORAGE);
                ActivityCompat.requestPermissions(this, new String[]{READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE,MANAGE_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STORAGE);
            } else {
                Log.d(TAG,"第二层else");
                //查询版本信息
                queryUpdateInfo();
            }
        } else {
            Log.d(TAG,"第一层else");
            //查询版本信息
            queryUpdateInfo();
        }
    }

    private void requestInstallPermision(){
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            boolean permission = getPackageManager().canRequestPackageInstalls();
            if (permission) {
                requestStoragePermision();
            } else {
                new AlertDialog.Builder(this)
                        .setTitle("权限申请")
                        .setMessage("应用安装权限申请！")
                        .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                    Uri packageURI = Uri.parse("package:" + getPackageName());
                                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                                    startActivityForResult(intent, REQUEST_INSTALL);
                                }
                            }
                        }).setNegativeButton("取消",null ).show();
            }
        }else{
            requestStoragePermision();
        }

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            int permission = checkSelfPermission("android.permission.REQUEST_INSTALL_PACKAGES");
//            //没权限弹出是否允许权限弹窗
//            if (permission != PackageManager.PERMISSION_GRANTED) {
//                //requestPermissions(new String[]{"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"}, REQUEST_WRITE_EXTERNAL_STORAGE);
//                ActivityCompat.requestPermissions(this, new String[]{REQUEST_INSTALL_PACKAGES}, REQUEST_INSTALL);
//            } else {
//                //查询版本信息
//                requestStoragePermision();
//            }
//
//        } else {
//            requestStoragePermision();
//        }
    }

    //查询登录信息
    private void queryUpdateInfo(){
        CommonUtil.showPress(this);
        QueryVersionTask queryVersionTask = new QueryVersionTask(LoginActivity.this);
        queryVersionTask.execute();
    }
    //绑定数据
    private void BindData(Context context) {
        //test
        //updateInfo = null;
        //test
        if (updateInfo == null) {
            //查询结果为空则放弃升级
            init();
        } else {
            if ("0".equals(updateInfo.needUpdate)) {
                //已经是最新版本不需要升级
                init();
            }else{
                //询问是否下载和更新
                try {
                    //初始化下载组件
                    mUpdateManager = new UpdateManager(this, updateInfo);
                    //弹窗询问
                    showUpdateNoticeDialog(updateInfo.forceUpdate);
                }catch (Exception ex){
                    Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    //初始化登录界面
    private void init(){
        loginDBHelper =  new LoginDBHelper(this,"config.db",null,1);
        accountText = findViewById(R.id.account);
        passwordText = findViewById(R.id.password);
        scSequenceText = findViewById(R.id.tv_login_scSequence);
        cb_login_remember =  findViewById(R.id.cb_login_remember);
        Button bt_login= findViewById(R.id.login);
        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "点击了登录按钮");
                //启动后台任务
                LoginTask loginTask = new LoginTask();
                loginTask.execute(accountText.getText().toString(),passwordText.getText().toString());
            }
        });
        TextView tv_set= findViewById(R.id.bt_login_set);
        tv_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, StringInputActivity.class);
                intent.putExtra("title","请输入服务地址【例如：127.0.0.1:8080】:");
                intent.putExtra("rowNum",0);
                intent.putExtra("data", SysParameter.WS_IPandPort);
                startActivityForResult(intent,REQUEST_SETURL);
            }
        });

        if(!SysParameter.allSetWsurl)
            tv_set.setVisibility(View.INVISIBLE);

        //设备号
        GetDeviceId();

        //URL
        if(SysParameter.allSetWsurl)
            SysParameter.WS_IPandPort = loginDBHelper.GetParm(LoginDBHelper.Parm_Url);
        //用户名
        SysParameter.user = loginDBHelper.GetParm(LoginDBHelper.Parm_UserName);
        //密码
        SysParameter.password = loginDBHelper.GetParm(LoginDBHelper.Parm_Password);
        //读取历史用户名密码
        String remember = loginDBHelper.GetParm(LoginDBHelper.Parm_Remember);
        cb_login_remember.setChecked(remember.equals("1"));

        if (remember.equals("1")) {
            accountText.setText(SysParameter.user);
            passwordText.setText(SysParameter.password);
        }
        //判断登录状态
        String loginstate = loginDBHelper.GetParm(LoginDBHelper.Parm_LoginState);
        Log.d(TAG, loginstate.toString());

        if(loginstate.equals("1")) {
//            LoginTask loginTask = new LoginTask();
//            loginTask.execute( SysParameter.user, SysParameter.password);
            //已登录未注销则直接跳转
            Intent intent = new Intent(LoginActivity.this, MainMenuActivity.class);
            startActivity(intent);
            LoginActivity.this.finish();
        }

        //异常捕获
        CrashHandlerUtil.getInstance().init(getApplicationContext());
    }

    //显示版本信息，询问是否更新升级 forceUpdate 0 非必须升级 1 必须升级
    private void showUpdateNoticeDialog(String forceUpdate) {
        //1.创建一个Dialog对象,去除标题栏
        final Dialog mDialog = new Dialog(this);
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //2.填充布局,将自定义布局设置进去
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.dialog_updateinfo, null);
        mDialog.setContentView(dialogView);
        //3.设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        Window window = mDialog.getWindow();
        lp.copyFrom(window.getAttributes());
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
        mDialog.show();
        window.setAttributes(lp);
        //4、设置点击其它地方不让消失弹窗
        mDialog.setCancelable(false);
        //5、初始化控件
        //下拉列表
        TextView tv_versionName = dialogView.findViewById(R.id.tv_versionName);
        tv_versionName.setText("（" + SysParameter.currentVersion + " 至 " + updateInfo.versionName + "）");
        TextView tv_versionInfo = dialogView.findViewById(R.id.tv_versionInfo);
        tv_versionInfo.setText(updateInfo.versionInfo);

        TextView tv_ok = dialogView.findViewById(R.id.tv_ok);
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                mUpdateManager.showDownloadDialog();
            }
        });
        TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
        if ("0".equals(forceUpdate)) {
            tv_cancel.setVisibility(View.VISIBLE);
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDialog.dismiss();
                    //如果取消下载，则初始化当前版本
                    init();
                }
            });
        } else {
            tv_cancel.setVisibility(View.GONE);
        }
    }

    //对话框返回处理
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //得到新Activity 关闭后返回的数据
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_SETURL:
                    SysParameter.WS_IPandPort = data.getExtras().getString("result");
                    loginDBHelper.SetParm(LoginDBHelper.Parm_Url, SysParameter.WS_IPandPort);
                    break;
                case REQUEST_INSTALL:
                    requestStoragePermision();
                    break;
            }
        }
    }

    //授权处理
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        //Toast.makeText(getApplicationContext(), requestCode + ":" + permissions[0], Toast.LENGTH_LONG).show();
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_READ_PHONE_STATE:
                if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    SetDeviceId();
                }
                break;
            case REQUEST_EXTERNAL_STORAGE:
                if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    queryUpdateInfo();
                }
                break;
            case REQUEST_INSTALL:
                if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    requestStoragePermision();
                } else {
                    Toast.makeText(getApplicationContext(), "授权失败", Toast.LENGTH_LONG).show();
                }
                break;
            default:
                break;
        }
    }

    //授权标记
    private static final int REQUEST_READ_PHONE_STATE = 1;
    private static final int REQUEST_EXTERNAL_STORAGE = 2;
    private static final int REQUEST_INSTALL = 3;
    private static final int REQUEST_SETURL = 4;
    //获取设备唯一id
    private void GetDeviceId() throws SecurityException {
        //动态赋权
        int permissionCheck = ContextCompat.checkSelfPermission(this, READ_PHONE_STATE);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
        } else {
            SetDeviceId();
        }
    }
    //设置设备唯一id
    private void  SetDeviceId() throws SecurityException {
        try {
            String deviceId = "无";
            //获取设备唯一ID,该方法已经无法获取唯一id，使用下面的方法不需要申请权限即可拿到唯一值
//            TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
//            deviceId = telephonyManager.getDeviceId();
            deviceId = Settings.Secure.getString(
                    getApplicationContext().getContentResolver(),
                    Settings.Secure.ANDROID_ID
            );

//            if (deviceId == null) {
//                deviceId = Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
//            }
            //获取手机品牌型号
            String model = android.os.Build.MODEL;
            String brand = android.os.Build.BRAND;

            deviceId = deviceId + ";" + model + ";" + brand + ";" + SysParameter.currentVersion;

            Log.d("BugCao", "deviceId:" + deviceId);

            SysParameter.ScSequence = deviceId;

        } catch (Exception ex) {
            SysParameter.ScSequence = "无";
            Toast.makeText(getApplicationContext(), "获取设备号失败：" + ex.getMessage(), Toast.LENGTH_LONG).show();
        }
        scSequenceText.setText(SysParameter.ScSequence);
    }

    //登录服务
    class LoginTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) {
            String result = "成功";
            // 登录
            try {
                result = WebServiceHelper.Login(params[0],params[1]);
            } catch (Exception e) {
                result = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return result;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            //解析结果
            if (result.contains("成功")) {
                Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_LONG).show();
                //保存参数
                boolean remember = cb_login_remember.isChecked();
                loginDBHelper.SetParm(LoginDBHelper.Parm_Remember,remember?"1":"0");
                loginDBHelper.SetParm(LoginDBHelper.Parm_UserName,accountText.getText().toString());
                loginDBHelper.SetParm(LoginDBHelper.Parm_Password,passwordText.getText().toString());
                SysParameter.user = accountText.getText().toString();
                SysParameter.password =  passwordText.getText().toString();
                //保存登录状态
                loginDBHelper.SetParm(LoginDBHelper.Parm_LoginState,"1");
                //启动心跳服务
                //HeartBeatUtil.startPollingService(LoginActivity.this,SysParameter.heartBeatSecconds,HeartBeatService.class);
                //跳转
                Intent intent = new Intent(LoginActivity.this, MainMenuActivity.class);
                startActivity(intent);
                LoginActivity.this.finish();
            }
            else
            {
                Toast.makeText(getApplicationContext(), "登录失败："+result, Toast.LENGTH_LONG).show();
            }
        }
    }

    //查询版本服务
    class QueryVersionTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        QueryVersionTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                updateInfo = WebServiceHelper.GetUpdateVersion(SysParameter.currentVersion);
                Log.d(TAG, updateInfo.toString());
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

}
